package com.feihong.activity.service.impl;

import com.feihong.activity.entity.AreaInfo;
import com.feihong.activity.entity.AuthDemo;
import com.feihong.activity.entity.Sensor;
import com.feihong.activity.entity.SensorDTO;
import com.feihong.activity.mapper.FeedingAreaMapper;
import com.feihong.activity.service.BackFeedingService;
import com.feihong.common.service.DefaultServiceImpl;
import com.feihong.common.util.FileUtils;
import com.feihong.common.util.StringOurUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Filter
 */
@Service
public class BackFeedingServiceImpl extends DefaultServiceImpl implements BackFeedingService {
    @Resource
    private FeedingAreaMapper feedingAreaMapper;
    @Resource
    private AuthDemo auth;
    @Resource
    private AreaInfo area;


    @Override
    public void shareEquipmentByCity(String pathName, String batchName) throws IllegalAccessException, IOException {
        feedingAreaMapper.addPushTask(batchName,area.getUrl());
        Integer taskId = feedingAreaMapper.getMaxTaskIdByCity();
        feedingAreaMapper.addAuthentication(taskId, area.getLoginUrl());
        feedingAreaMapper.addAuthUserName(area.getLoginName(), taskId);
        feedingAreaMapper.addAuthPassword(area.getLoginPassword(), taskId);
        feedingAreaMapper.addAuthPlatformId(auth.getPlatformId(),taskId);
        feedingAreaMapper.addRequestHeader(taskId);
        Map<String, String> map = FileUtils.getMap(pathName,taskId);
        feedingAreaMapper.addPushRangeFieldRel(taskId, map);
        Sensor sensor = new Sensor();
        sensor.setDataCode("REL");
        sensor.setPostTime("TIME");
        buildField(taskId, sensor);
        feedingAreaMapper.addAll(taskId,auth.getSheetName());
    }

    private void buildField(Integer newTaskId, Sensor sensor) throws IllegalAccessException {
        Field[] declaredFields = sensor.getClass().getDeclaredFields();
        List<SensorDTO> list = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            SensorDTO sensorDTO = new SensorDTO();
            sensorDTO.setField(declaredField.getName());
            sensorDTO.setValue((String) declaredField.get(sensor));
            sensorDTO.setUnderField(StringOurUtils.camel2under(declaredField.getName()));
            sensorDTO.setNewTaskId(newTaskId);

            if ("dataCode".equals(declaredField.getName())) {
                sensorDTO.setUnderField("product_key");
            }
//            else if("sensorType".equals(declaredField.getName())){
//
//            }
            list.add(sensorDTO);
        }
        if (list.size() != 0) {
            feedingAreaMapper.addFieldReplace(list);
        }
    }
}
